package com.chen.usersys.controller;

import com.chen.usersys.domain.ResponseCommon;
import com.chen.usersys.domain.User;
import com.chen.usersys.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户控制器
 */
@Controller
//@RequestMapping("/api")
public class UserController {


    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @GetMapping("/selectAll")
    public String selectAllUser(Model model) {
        List<User> users = userService.selectAllUser();
        // 密码脱敏
        users.stream().forEach(item -> {
            item.setUPwd("******");
        });
        model.addAttribute("users", users);
        return "list";
    }


    /**
     * 登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public ResponseCommon login(@RequestParam(name = "uName") String username, @RequestParam(name = "uPwd") String password, HttpServletRequest request) {
        return userService.login(username, password, request);
    }

    /**
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/selectById")
    public String selectById(Integer id, Model model, String type) {
        User user = userService.selectById(id);
        model.addAttribute("user", user);
        model.addAttribute("type", type);
        return StringUtils.isEmpty(type) ? "detailUser" : "update";
    }


    //新增用户
    @PostMapping("/save")
    @ResponseBody
    public String saveUser(User formData) {
        return userService.insertUser(formData);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public String deleteUserById(@PathVariable Integer id) {
        userService.deleteUserById(id);
        // 跳转
        return "redirect:/selectAll";
    }


    @PostMapping("/update")
    @ResponseBody
    public Integer updateUserById(User user) {
        return userService.updateUser(user);
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "/index";
    }
}
